package cn.wen.java.sql.ds;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Title: 数据仓库辅助。
 * <p>
 * Description: 主要生产数据仓库实体及提供相关辅助。
 * <p>
 * Copyright: Copyright (c) 2010-2012
 * 
 * @author <a href="mailto:ct_wen@qq.com">ctwen</a>, 温承瑭
 * @version Revision: 1.0 Date: 2011/5/17 description：初完成。
 *          </P>
 */
public class DSHelper {

    /**
     * 创建Datastore，将ResultSet转换成Datastore；
     * <P>
     * 注：该方法不负责关闭ResultSet，但某些ResultSet实现类的内部机制会在rs.next()无效时关闭。<br>
     * 如：oracle.jdbc.driver.OracleResultSetImpl
     * <P>
     * 
     * @param rs ResultSet
     * @return Datastore 数据集
     * @throws SQLException
     */
    public static Datastore createDatastoreByResultSet(ResultSet rs) throws SQLException {
	ResultSetMetaData rsmd = rs.getMetaData();

	int count = rsmd.getColumnCount();
	InfoColumn[] infoColumns = new InfoColumn[count];
	int index;
	for (index = 0; index < count; index++) {
	    infoColumns[index] = getInfoColumn(rsmd, index);
	}

	ArrayList<Map<String, DataCell>> dslm = new ArrayList<Map<String, DataCell>>();
	ArrayList<List<DataCell>> dsll = new ArrayList<List<DataCell>>();

	while (rs.next()) {
	    Map<String, DataCell> rowMap = new HashMap<String, DataCell>();
	    List<DataCell> rowList = new ArrayList<DataCell>();

	    for (index = 0; index < count; index++) {
		DataCell dataCell = new DataCell(rs.getObject(index + 1));
		rowMap.put(infoColumns[index].getLabel(), dataCell);
		rowList.add(dataCell);
	    }

	    dslm.add(rowMap);
	    dsll.add(rowList);
	}

	Datastore ds = new Datastore(dslm, dsll);
	ds.setInfoColumns(infoColumns);
	return ds;
    }

    private static InfoColumn getInfoColumn(ResultSetMetaData rsmd, int index) throws SQLException {
	index++;

	InfoColumn infoColumn = new InfoColumn();

	infoColumn.setLabel(rsmd.getColumnLabel(index));
	infoColumn.setName(rsmd.getColumnName(index));
	infoColumn.setType(rsmd.getColumnType(index));
	infoColumn.setTypeName(rsmd.getColumnTypeName(index));
	infoColumn.setSchemaName(rsmd.getSchemaName(index));
	infoColumn.setTableName(rsmd.getTableName(index));

	return infoColumn;
    }

    /**
     * 可将Datastore的所有数据转为JSON格式并输出给调用者。
     * 
     * @param ds Datastore
     * @return JSON数据。
     */
    public static String toJson(Datastore ds) {
	StringBuilder json = new StringBuilder("[");
	
	for (Map<String, DataCell> row : ds.getDslm()) {
	    json.append("{");
	    for (Entry<String, DataCell> cell : row.entrySet()) {
		json.append("\"").append(cell.getKey()).append("\":").append(cell.getValue().toJson()).append(",");
	    }
	    json.deleteCharAt(json.length() - 1).append("},\n");
	}
	
	return json.delete(json.length() - 2, json.length()).append("]").toString();
    }
    
}
